package com.blb.educourseservice.courseLinsten;

import com.alibaba.fastjson.JSON;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.blb.config.RabbitMQConfig;
import com.blb.educourseservice.service.ICourseService;
import com.blb.pojo.Course;
import com.blb.pojo.ResponseResult;
import com.xpand.starter.canal.annotation.CanalEventListener;
import com.xpand.starter.canal.annotation.ListenPoint;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;

/**
 * 事件监听器
 */
@CanalEventListener
public class CanalListener {
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private ICourseService iCourseService;

    /**
     * 监听 erp数据库的customer表
     */
    @ListenPoint(schema = "edu_course",table = "course")
    public void updateData(CanalEntry.EventType eventType, CanalEntry.RowData rowData){
        if(eventType.name().equals("INSERT")||eventType.name().equals("UPDATE")){
            System.out.println(rowData.getAfterColumnsList().size());
            rowData.getAfterColumnsList().forEach(course ->{
                System.out.println(course);
              if("id".equals(course.getName())){
                  Course course1 = iCourseService.getCourseById(Long.valueOf(course.getValue()));
                  String json= JSON.toJSONString(course1);
                  rabbitTemplate.convertAndSend(RabbitMQConfig.COURSE_EXCHANGE,RabbitMQConfig.KEY_COURSE_SAVE,json);
                  return;
              }
            });
        }else if(eventType.name().equals("DELETE")){
            rowData.getBeforeColumnsList().forEach(course ->{
                if("id".equals(course.getName())){
                    rabbitTemplate.convertAndSend(RabbitMQConfig.COURSE_EXCHANGE,RabbitMQConfig.KEY_COURSE_REMOVE,course.getValue());
                   return;
                }
            });
        }
    }
}
